package classReflectDemo;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Ajie
 * @date 2021-03-18
 * @function
 *
 * 结论：
 * Son extends Father
 * classReflectDemo.Father#strField
 * classReflectDemo.Son#strField
 * 是2个字段，没关系。
 *
 * classReflectDemo.Father#Name()
 * classReflectDemo.Son#Name()
 * 方法重载，按照初始化的对象的方法来执行。
 */
public class Test_Field_Method_Son_Father {

    public static void main(String[] args) {

        Son son = new Son();

        System.out.println("instanceof father:"+(son instanceof Father)+"  instanceof son:"+(son instanceof Son));
        printField(son);

        System.out.println("\n");
        System.out.println("father str:"+((Father)son).strField);
        System.out.println("son str:"+son.strField);

        System.out.println("father TAG:"+((Father)son).TAG);
        System.out.println("son TAG:"+son.TAG);

        System.err.print("father method:");((Father)son).Name();
        System.err.print("son method:");son.Name();
    }

    private static void printField(Object obj) {
        System.out.println("class:" + obj);
        try {
            List<Field> fieldList = new ArrayList<>();
            Class tempClass = obj.getClass();
            while (tempClass != null) {//当父类为null的时候说明到达了最上层的父类(Object类).
                fieldList.addAll(Arrays.asList(tempClass.getDeclaredFields()));
                tempClass = tempClass.getSuperclass(); //得到父类,然后赋给自己
            }

            for (int i = 0; i < fieldList.size(); i++) {
                Field declaredField = fieldList.get(i);
                declaredField.setAccessible(true);
                System.out.println(declaredField.getName() + "  --> " + declaredField.get(obj));
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
class Father{
    String strField = "fatherStr";
    static final String TAG = "Father";

    void Name(){
        System.out.println("father name");
    }

}

class Son extends Father {
    static final String TAG = "Son";
    String strField = "sonStr";

    @Override
    void Name() {
        System.out.println("son name");
    }
}
